package com.lanbu.web.controller.system;

import java.io.*;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;


import com.lanbu.common.config.LanBuConfig;
import com.lanbu.common.core.domain.entity.SysUser;
import com.lanbu.common.exception.ServiceException;
import com.lanbu.common.utils.DateUtils;
import com.lanbu.common.utils.StringUtils;
import com.lanbu.common.utils.file.FileUploadUtils;
import com.lanbu.framework.config.ServerConfig;
import com.lanbu.system.domain.dto.uploadImageDTO;
import com.lanbu.system.utils.BaseCodeException;
import com.lanbu.system.utils.Excel;
import com.lanbu.system.utils.ExcelDataEntry;
import com.lanbu.system.utils.ExcelSheet;

import com.lanbu.system.service.*;
import com.lanbu.system.utils.CustomMultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.lanbu.common.core.controller.BaseController;
import com.lanbu.common.core.domain.AjaxResult;
import org.springframework.web.multipart.MultipartFile;

/**
 * 产品品类Controller
 *
 * @author ruoyi
 * @date 2024-09-30
 */
@RestController
@RequestMapping("/user/upload")
@Api(tags = "系统:用户管理")
public class UploadUserController extends BaseController
{

   /* @Autowired
    private ExcelImportService excelImportService;*/
   @Autowired
   private ServerConfig serverConfig;
    @Autowired
    private ISysUserService userService;


    @Value("${imgUrl.profile}")
    private String imgUrl;
    @Value("${imgUrl.pathexcel}")
    private String path;

    @Autowired
    private ISysConfigService configService;
    public UploadUserController() throws UnsupportedEncodingException {
    }



    /**
     * 接收读取文件
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @ApiOperation("execl用户图片上传")
    @PostMapping("/upload")
    public AjaxResult uploadExcel(@RequestParam("file")  MultipartFile file, boolean updateSupport) throws BaseCodeException, IOException {


        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        List<SysUser>  sysUsers =new ArrayList<>();
        Date now = new Date(); // 获取当前日期和时间
        String dateStr = DateUtils.parseDateToStr("yyyyMMddHHmmss",now);
        //获取文件名 : file.getOriginalFilename();
        String fileName = file.getOriginalFilename();
       // String path = "/data/home/qxsb/excel";
        //上传路径保存设置
      //  String path = "D:"+File.separator+"file";
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        //上传文件地址
        // System.out.println("上传文件保存地址："+realPath);
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        File newFile = new File(realPath +File.separator+dateStr+"_"+ fileName);
        file.transferTo(newFile);
        String filePath = realPath +File.separator+dateStr+"_"+ fileName;
//        String imageTargetPath = imgUrl+"/upload"+"/"+year+"/"+ month+"/"+day;
        //加应该前缀
        String imageTargetPath = imgUrl+"/upload";

            Excel excel = new Excel(filePath,imageTargetPath);
            ExcelSheet excelSheet = excel.getSheet(0,1);
            List<Map<Integer, ExcelDataEntry>> rowDataList = excelSheet.getRowDataList();
            Map<Integer, ExcelDataEntry> headerRow = rowDataList.get(0);

            List<String> headValues=new ArrayList<>();
            for (int i = 0; i < headerRow.size(); i++) {
                headValues.add(headerRow.get(i).getData().toString());
            }

            for (int i = 1; i < rowDataList.size(); i++) {
                Map<Integer, ExcelDataEntry> dataRow = rowDataList.get(i);
                LinkedHashMap<String, String> rowData = new LinkedHashMap<>();
                SysUser sysUser =new SysUser();
                if (dataRow.size()==0) {
              //  codeRecord.setStatus(codeStatus.CODE_STATUS_CODE_SEND_FAILED);
                 //   codeRecordService.insertCodeRecord(codeRecord);
                    return AjaxResult.error("文件内容有误,数据中不要有空行");
                }

                // 验证是否存在这个用户
  //              SysUser u = userService.selectUserByUserName(dataRow.get(1).getData().toString());
//                if (StringUtils.isNull(u))
//                {
                //   sysUser.setDeptId(Long.valueOf(String.valueOf(dataRow.get(2).getData())));
                //姓名
                sysUser.setUserName(String.valueOf(dataRow.get(0).getData()));
                sysUser.setNickName(String.valueOf(dataRow.get(0).getData()));
                //学号
                String value = String.valueOf(dataRow.get(1).getData());
                double sid = Double.parseDouble(value);
                sysUser.setStudentId((long) sid);
                // 重命名后的路径
                String renamedPath = renameImageAndReplace(dataRow.get(6).getData().toString(), String.valueOf(dataRow.get(0).getData())+(long)sid+".jpeg");
                // 原始文件
                File originalFile = new File(renamedPath);
                byte[] fileContent = Files.readAllBytes(originalFile.toPath());
                CustomMultipartFile multipartFile = new CustomMultipartFile(
                        fileContent,
                        originalFile.getName(),
                        originalFile.getName(),
                        "text/plain"
                );

                //                // 上传文件路径
                String filePath1 = LanBuConfig.getUploadPath();
//                // 上传并返回新文件名称
                String fileName1 = FileUploadUtils.upload(filePath1, multipartFile);
              String url = serverConfig.getUrl() + fileName1;
                // 打印重命名后的路径
                if (renamedPath != null) {
                    System.out.println("重命名后的图片路径为：" + renamedPath);
                } else {
                    System.out.println("图片重命名失败！");
                }
                //人脸图片
                sysUser.setFaceImage(fileName1);

                for (int j = 0; j < headerRow.size(); j++) {
                    if (dataRow.get(j)!=null && dataRow.get(j).getDataType()=="File"){

                        dataRow.get(j).setData("/profile/"+dataRow.get(j).getData().toString().substring(imgUrl.length()).replace(File.separator,"/"));
                    }
                    String cellData = dataRow.get(j)==null? null:dataRow.get(j).getData().toString();
                    rowData.put(headerRow.get(j).getData().toString(),cellData);
                }
                try {
                //姓别
                String valueSex = String.valueOf(dataRow.get(2).getData());
                double sidSex = Double.parseDouble(valueSex);
                int intSex = (int) sidSex;
                sysUser.setSex(String.valueOf(intSex));
                //年级
                    String grade = String.valueOf(dataRow.get(3).getData());
                    grade =     processValue(grade);
                    sysUser.setGrade(grade);
                //班级
                    String classes = String.valueOf(dataRow.get(4).getData());
                    classes =     processValue(classes);
                    sysUser.setClasses(classes);
                //年龄
                String valueAge = String.valueOf(dataRow.get(5).getData());
                double sidAge = Double.parseDouble(valueAge);
                sysUser.setPassword(password);
                sysUser.setAge((long) sidAge);
                    sysUsers.add(sysUser);
            }catch (Exception e){
                //  codeRecord.setStatus(codeStatus.CODE_STATUS_CODE_SEND_FAILED);
                //codeRecordService.insertCodeRecord(codeRecord);
                e.printStackTrace();
                return AjaxResult.error("文件内容有误,数据中不要有空列");
            }

            }

            for (SysUser user : sysUsers)
            {
                try
                {
                    // 验证是否存在这个用户
                    SysUser u = userService.selectUserByStudentId(user.getStudentId());
                    if (StringUtils.isNull(u))
                    {

                        userService.insertUser(user);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、学生 " + user.getStudentId() + " 导入成功");
                    }
                    else if (updateSupport)
                    {

                        userService.updateUser(user);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、学生 " + user.getStudentId() + " 更新成功");
                    }
                    else
                    {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、学生 " + user.getStudentId() + " 已存在");
                    }
                }
                catch (Exception e)
                {
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、学生 " + user.getStudentId() + " 导入失败：";
                    failureMsg.append(msg + e.getMessage());

                }
            }
            if (failureNum > 0)
            {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                throw new ServiceException(failureMsg.toString());
            }
            else
            {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            }
            return AjaxResult.success(successMsg.toString());


    }
    public static String renameImageAndReplace(String originalPath, String newFileName) {
        try {
            // 原始文件
            File originalFile = new File(originalPath);

            // 检查原始文件是否存在
            if (!originalFile.exists()) {
                System.out.println("原始文件不存在：" + originalPath);
                return null;
            }

            // 获取文件所在目录
            String directory = originalFile.getParent();

            // 拼接新的文件路径
            String newFilePath = directory + File.separator + newFileName;

            // 目标文件对象
            File newFile = new File(newFilePath);

            // 如果目标文件已存在，则删除它
            if (newFile.exists()) {
                if (!newFile.delete()) {
                    System.out.println("无法删除已存在的文件：" + newFilePath);
                    return null;
                }
            }

            // 使用 Files.copy 复制文件，并指定覆盖选项
            Files.copy(originalFile.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

            System.out.println("新文件已创建：" + newFilePath);
            return newFilePath;

        } catch (IOException e) {
            System.out.println("文件操作失败：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    public static String processValue(Object value) {
        if (value instanceof String) {
            String strValue = (String) value;
            try {
                // 使用NumberFormat来解析字符串为Number
                Number number = NumberFormat.getNumberInstance(Locale.US).parse(strValue);

                // 检查Number是否是整数（即没有小数部分）
                if (number instanceof Double || number instanceof Float) {
                    double doubleValue = ((Number) number).doubleValue();
                    if (doubleValue == Math.floor(doubleValue)) {
                        // 如果是整数，则转换为int并返回其字符串表示
                        return String.valueOf((int) doubleValue);
                    }
                } else {
                    // 对于其他Number类型（如Integer, Long等），直接返回其字符串表示
                    return number.toString();
                }

                // 如果到达这里，说明是一个有有效小数部分的浮点数
                return strValue;
            } catch (ParseException e) {
                // 如果字符串不是有效的数字格式，则直接返回原始字符串
                return strValue;
            }
        } else if (value instanceof Number) {
            // 如果值是Number类型，则检查其是否为整数
            Number numValue = (Number) value;
            if (numValue instanceof Double || numValue instanceof Float) {
                double doubleValue = numValue.doubleValue();
                if (doubleValue == Math.floor(doubleValue)) {
                    // 如果是整数，则转换为int并返回其字符串表示
                    return String.valueOf((int) doubleValue);
                }
            }
            // 对于其他情况，直接返回其字符串表示
            return numValue.toString();
        } else {
            // 如果值既不是String也不是Number，则直接返回其toString()表示
            return value.toString();
        }
    }

    @ApiOperation("图片上传")
    @PostMapping("/uploadImage")
    public AjaxResult uploadImage(@RequestBody  uploadImageDTO uploadImageDTO) throws BaseCodeException, IOException {
        // 解码Base64字符串为字节数组
        byte[] decodedBytes = Base64.getDecoder().decode(uploadImageDTO.getBase());

        // 创建MockMultipartFile对象
        CustomMultipartFile multipartFile = new CustomMultipartFile(
                decodedBytes,
                uploadImageDTO.getName()+uploadImageDTO.getStudentId()+".jpeg",
                uploadImageDTO.getName()+uploadImageDTO.getStudentId()+".jpeg",
                "text/plain"
        );
        //                // 上传文件路径
        String filePath1 = LanBuConfig.getUploadPath();
//                // 上传并返回新文件名称
        try {
            String fileName1 = FileUploadUtils.upload(filePath1, multipartFile);

            return success(fileName1);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }



    }
